<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1" import="java.util.*, myclasses.*, support.*, java.sql.*"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Confirmation</title>
</head>
<body>
<%
	Student stud = (Student)session.getAttribute("student");

	try {
		Class.forName("org.postgresql.Driver");
	} catch(Exception e) {
		out.println("org.postgresql.Driver Exception!");
	}
	
	try {
		String serverName = "localhost:5432";
	    String mydatabase = "ThirdBase";
	    String url = "jdbc:postgresql://" + serverName + "/" + mydatabase; 
	    String username = "SweetAss";
	    String password = "1234";
	    Connection conn = DriverManager.getConnection(url, username, password);
		Statement stmt = conn.createStatement();
		//insert address
		Address a = stud.getAddress();
		//TAKE CARE OF NOT US NULL BUG?
		int ret = stmt.executeUpdate("INSERT INTO address (street,number,city,state,zip,areacode,tlfcode,residence) VALUES ('" +
		a.getStreet() + "','" + a.getPhone() + "','" + a.getCity() + "','" + a.getState() + "','" +
		a.getZip() + "','" + a.getArea() + "','" + a.getCountryCode() + "'," + stud.getResidenceId() + ")");
		
		ResultSet rset = stmt.executeQuery("SELECT id FROM address ORDER BY id DESC LIMIT 1");
		rset.next();
		int addressPk = Integer.parseInt(rset.getString(1)); 
		
		//starts at pk 2??
		ret = stmt.executeUpdate("INSERT INTO applicant (firstname,middleinitial,lastname,address,citizenship,specialization) VALUES ('" +
		stud.getFirstName() + "','" + stud.getMiddleInitial() + "','" + stud.getLastName() + "'," +
		addressPk + "," + stud.getCitizenshipId() + "," + stud.getSpecialization() + ")");
		
		rset = stmt.executeQuery("SELECT id FROM applicant ORDER BY id DESC LIMIT 1");
		rset.next();
		int applicantPk = Integer.parseInt(rset.getString(1));
		
		
		LinkedHashSet<Degree> degs = stud.getDegrees();		
		for (Degree d : degs) {
	
	ret = stmt.executeUpdate("INSERT INTO degree (month,year,gpa,applicant,title,university,major) VALUES ('" +
		d.getMonth() + "','" + d.getYear() + "','" + d.getGpa() +  "'," + applicantPk + "," + d.getName() + "," +
		d.getUniversity() + "," + d.getDiscipline() + ")");
		}
		
		rset.close();
		stmt.close();
		conn.close();
	
	} catch(SQLException e) {
		e.printStackTrace();
		out.println("Connection exception.");
		
		//something went wrong
		out.println("<meta HTTP-EQUIV=\"REFRESH\" content=\"0; url=http://localhost:8080/GradSchoolApp/fail.html\">");
	}
%>
<h3>Application succeeded!</h3>
</body>
</html>